package com.javaweb.db.help;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import com.javaweb.annotation.sql.Column;
import com.javaweb.constant.CommonConstant;
import com.javaweb.enums.CamelCaseEnum;
import com.javaweb.exception.ServiceException;
import com.javaweb.util.core.StringUtil;

public class SqlHelpUtil {
	
	/**
	 * 获取数据库字段名称
	 * <P>
	 * 一些开发工具（如eclipse）或操作系统等，尤其是在低版本下，有时无法得到想要的属性，而是会得到lambda$0
	 * @param <T>
	 * @param lambda Function参数
	 * @return String 数据库字段名称
	 */
	public static <T> String getColumnName(SqlColumnFunction<T> lambda) {
		try {
			Method method = lambda.getClass().getDeclaredMethod("writeReplace");
			method.setAccessible(CommonConstant.TRUE);
			SerializedLambda serializedLambda = (SerializedLambda) method.invoke(lambda);
			String implMethodName = serializedLambda.getImplMethodName();
			implMethodName = implMethodName.substring(3,implMethodName.length());//get和set都占3个长度
			implMethodName = StringUtil.camelCaseConvert(implMethodName,CamelCaseEnum.FIRST_WORD_LOWER);
			Field field = Class.forName(serializedLambda.getImplClass().replaceAll(CommonConstant.FORWARD_SLASH,CommonConstant.DOT)).getDeclaredField(implMethodName);
			Column column = field.getAnnotation(Column.class);
			return column.name();
		}catch (Exception e) {
			throw new ServiceException(e.getMessage());
		}
	}

}
